package com.huiyin.ui.classic;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.JsonSyntaxException;
import com.huiyin.AppContext;
import com.huiyin.R;
import com.huiyin.UIHelper;
import com.huiyin.adapter.UploadImageAdapter;
import com.huiyin.api.RequstClient;
import com.huiyin.api.URLs;
import com.huiyin.base.BaseCameraActivity;
import com.huiyin.bean.ImageData;
import com.huiyin.bean.ReportBaseInfoTitle;
import com.huiyin.bean.ReportBaseInfoType;
import com.huiyin.dialog.UploadSuccessDialog;
import com.huiyin.ui.housekeeper.SelectApplyReasonWindow.IOnItemClick;
import com.huiyin.ui.store.StoreHomeActivity;
import com.huiyin.utils.DeviceUtils;
import com.huiyin.utils.ImageManager;
import com.huiyin.utils.JSONParseUtils;
import com.huiyin.utils.MathUtil;
import com.huiyin.utils.MyCustomResponseHandler;
import com.huiyin.utils.imageupload.ImageUpload.UpLoadImageListener;

/**
 * “我要举报”页面，用于客户填写举报信息
 * 
 * @author leizhiheng
 * 
 */
public class ReportActivity extends BaseCameraActivity implements OnClickListener, OnItemClickListener {
	private static final String TAG = "ReportActivity";

	private View mTitleLayout;
	private ImageView mIvShopIcon;
	private TextView mTvBack;
	private TextView mTvTitle;
	private TextView mTvShopName;
	private TextView mTvGoodsName;
	private TextView mTvGoodPrice;
	private TextView mTvReportCategory;
	private TextView mTvCategoryDescription;
	private TextView mTvreportThemes;
	private TextView mTvHandReport;
	private ImageView mIvGoodsImg;
	private ImageView mIvToStore;
	private TextView mTvInputNum;
	private EditText mEtReportMessage;

	/** 上传图片 **/
	private GridView uploadGridView;

	/** 图片上传适配器 **/
	private UploadImageAdapter uploadImageAdapter;

	private ArrayList<ReportBaseInfoType> mBaseInfoTypes;// 举报基本信息：类型
	private ArrayList<ReportBaseInfoTitle> mTitlesList;// 选择举报类型后对应的举报主题
	private int chosedTypeIndex;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_report);

		initData();
		initView();
	}

	private String goods_id;
	private String store_id;
	private String store_logo;
	private String store_name;
	private String goods_price;
	private String goods_name;
	private String goods_img;

	public void initData() {
		Intent intent = this.getIntent();
		if (intent != null) {
			/*
			 * 从BasicInformationFragment传递过来的部分商品信息
			 */
			Bundle bundle = intent.getExtras();
			goods_id = bundle.getString("goods_id");
			store_id = bundle.getString("store_id");
			store_logo = bundle.getString("store_logo");
			store_name = bundle.getString("store_name");
			goods_price = bundle.getString("goods_price");
			goods_name = bundle.getString("goods_name");
			goods_img = bundle.getString("goods_img");
		}
		mBaseInfoTypes = new ArrayList<ReportBaseInfoType>();
		loadReportBaseInfo();
	}

	public void initView() {
		mTitleLayout = findViewById(R.id.layout_ab);
		mTitleLayout.setFocusable(true);
		mTitleLayout.setFocusableInTouchMode(true);
		mTitleLayout.requestFocus();

		mIvShopIcon = (ImageView) findViewById(R.id.iv_shop_logo);
		mTvBack = (TextView) findViewById(R.id.ab_back);
		mTvTitle = (TextView) findViewById(R.id.ab_title);
		mTvShopName = (TextView) findViewById(R.id.tv_shop_name);
		mTvGoodsName = (TextView) findViewById(R.id.good_message);
		mTvGoodPrice = (TextView) findViewById(R.id.goods_price);
		mTvReportCategory = (TextView) findViewById(R.id.tv_report_catogery_message);
		mTvCategoryDescription = (TextView) findViewById(R.id.tv_report_catogery_description);
		mTvreportThemes = (TextView) findViewById(R.id.tv_report_theme_message);
		mTvHandReport = (TextView) findViewById(R.id.tv_handup_report);
		mIvToStore = (ImageView) findViewById(R.id.arrow_to_shop);
		mIvGoodsImg = (ImageView) findViewById(R.id.goods_icon);
		mEtReportMessage = (EditText) findViewById(R.id.et_report_message_input);
		mTvInputNum = (TextView) findViewById(R.id.tv_input_num);
		this.uploadGridView = (GridView) findViewById(R.id.upload_gridview);

		mIvShopIcon.setOnClickListener(this);
		mTvBack.setOnClickListener(this);
		mTvShopName.setOnClickListener(this);
		mTvReportCategory.setOnClickListener(this);
		mTvreportThemes.setOnClickListener(this);
		mTvHandReport.setOnClickListener(this);

		// 文本监听
		setTextChangeListener(mEtReportMessage, mTvInputNum, 200);

		int screenWidth = DeviceUtils.getWidthMaxPx(mContext);
		uploadImageAdapter = new UploadImageAdapter(mContext, screenWidth, 5);
		uploadGridView.setAdapter(uploadImageAdapter);
		uploadGridView.setOnItemClickListener(this);

		mTvTitle.setText("我要举报");
		if (!isMySelfStore()) {
			mIvToStore.setVisibility(View.VISIBLE);
			// 统一图片获取方式用于省流量设置
			ImageManager.LoadWithServer(URLs.IMAGE_URL + store_logo, mIvShopIcon);
		} else {
			mIvShopIcon.setImageResource(R.drawable.lehu);
		}
		// 统一图片获取方式用于省流量设置
		ImageManager.LoadWithServer(URLs.IMAGE_URL + goods_img, mIvGoodsImg);
		mTvShopName.setText(store_name);
		mTvGoodsName.setText(goods_name);
		mTvGoodPrice.setText(MathUtil.priceForAppWithSign(goods_price));
	}

	/*
	 * 获取举报的基本信息，如举报类型，举报主题
	 */
	private void loadReportBaseInfo() {
		Log.d(TAG, "loadReportBaseInfo ==>");
		RequstClient.loadReportInfo(new MyCustomResponseHandler(this, true) {

			@Override
			public void onSuccess(int statusCode, Header[] headers, String content) {
				super.onSuccess(statusCode, headers, content);
				UIHelper.cloesLoadDialog();
				try {
					JSONObject obj = new JSONObject(content);
					if (!obj.getString("type").equals("1")) {
						String errorMsg = obj.getString("msg");
						Toast.makeText(ReportActivity.this, errorMsg, Toast.LENGTH_SHORT).show();
						Log.d(TAG, "loadReportInfo failed");
						return;
					} else {
						// 获取举报信息
						if (mBaseInfoTypes == null) {
							mBaseInfoTypes = new ArrayList<ReportBaseInfoType>();
						} else {
							mBaseInfoTypes.clear();
						}
						mBaseInfoTypes = JSONParseUtils.parseReportBaseInfo(content);
						mTitlesList = mBaseInfoTypes.get(chosedTypeIndex).getTitleList();
						mTvCategoryDescription.setText(mBaseInfoTypes.get(0).getTypeDescription());

						mTvReportCategory.setText(mBaseInfoTypes.get(0).getTypeName());
						mTvReportCategory.setTag(mBaseInfoTypes.get(0).getTypeId());

						mTvreportThemes.setText(mTitlesList.get(0).getTitleName());
						mTvreportThemes.setTag(mTitlesList.get(0).getTitleId());
					}

				} catch (JsonSyntaxException e) {
					e.printStackTrace();
				} catch (JSONException e) {
					e.printStackTrace();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}

		});
	}

	@Override
	public void onClick(View arg0) {
		switch (arg0.getId()) {
		case R.id.ab_back:
			Log.d(TAG, "ab_back has been clicked");
			finish();
			break;
		case R.id.iv_shop_logo:
			break;
		case R.id.tv_shop_name:

			// 非自营店铺
			if (!isMySelfStore()) {
				Intent intent = new Intent(this, StoreHomeActivity.class);
				intent.putExtra(StoreHomeActivity.STORE_ID, MathUtil.stringToInt(store_id));
				startActivity(intent);
			}
			break;
		case R.id.tv_report_catogery_message:

			// 显示举报类型popwindow
			String typeId = getTag(mTvReportCategory);
			showReasonPopwindow(mTvReportCategory, getReportTypeMap(), typeId, new IOnItemClick() {

				@Override
				public void onItemClick(String id, String value) {
					mTvReportCategory.setText(value);
					mTvReportCategory.setTag(id);
					
					//获取举报类型对应的描述
					mTvCategoryDescription.setText(getReportTypeDesc(id));
				}
			});

			break;
		case R.id.tv_report_theme_message:

			// 显示举报主题popwindow
			String themeId = getTag(mTvreportThemes);
			showReasonPopwindow(mTvreportThemes, getThemeTypeMap(), themeId, new IOnItemClick() {

				@Override
				public void onItemClick(String id, String value) {
					mTvreportThemes.setText(value);
					mTvreportThemes.setTag(id);
				}
			});

			break;
		case R.id.tv_handup_report:

			
			//验证举报内容是否为空
			if(!validate()){
				return;
			}
			
			
			if(!uploadImageAdapter.hasNewUploadImgFile()){
				
				//提交举报
				String img = uploadImageAdapter.getImages();
				uploadReport(img);
				return;
			}
			
			
			//上传文件
			uploadImage(uploadImageAdapter.getDataList(), new UpLoadImageListener() {
				
				@Override
				public void UpLoadSuccess(ArrayList<String> netimageurls) {
					
					String newAppendImg = getImgs(netimageurls);
					String img = uploadImageAdapter.getImages();
					
					if(!TextUtils.isEmpty(img)){
						newAppendImg = newAppendImg + "," + img;
					}
					
					//提交举报
					uploadReport(newAppendImg);
				}
				
				@Override
				public void UpLoadFail() {
					showMyToast("图片上传失败");
				}
			});
			
			
			break;

		default:
			break;
		}
	}

	/**
	 * 输入验证
	 * @return
	 */
	private boolean validate(){
		if (mEtReportMessage.getText().toString().length() == 0) {
			Toast.makeText(this, "举报内容不能为空", Toast.LENGTH_SHORT).show();
			return false;
		}
		return true;
	}
	
	/**
	 * 是否为自营店铺
	 * 
	 * @return
	 */
	private boolean isMySelfStore() {
		double storeId = MathUtil.stringToDouble(store_id);
		return storeId <= 0;
	}

	
	/**
	 * 获取举报类型map
	 * 
	 * @return
	 */
	private String getReportTypeDesc(String typeId) {
		if (null != mBaseInfoTypes && mBaseInfoTypes.size() > 0) {

			String key = null;
			String value = null;
			for (int i = 0; i < mBaseInfoTypes.size(); i++) {
				key = mBaseInfoTypes.get(i).getTypeId() + "";
				if(key.equals(typeId)){
					return mBaseInfoTypes.get(i).getTypeDescription();
				}
			}
		}
		return "";
	}
	
	/**
	 * 获取举报类型map
	 * 
	 * @return
	 */
	private Map<String, String> getReportTypeMap() {
		Map<String, String> dataMap = new HashMap<String, String>();
		if (null != mBaseInfoTypes && mBaseInfoTypes.size() > 0) {

			String key = null;
			String value = null;
			for (int i = 0; i < mBaseInfoTypes.size(); i++) {
				key = mBaseInfoTypes.get(i).getTypeId() + "";
				value = mBaseInfoTypes.get(i).getTypeName();
				dataMap.put(key, value);
			}
		}
		return dataMap;
	}

	/**
	 * 获取举报类型map
	 * 
	 * @return
	 */
	private Map<String, String> getThemeTypeMap() {
		Map<String, String> dataMap = new HashMap<String, String>();
		if (null != mTitlesList && mTitlesList.size() > 0) {

			String key = null;
			String value = null;
			for (int i = 0; i < mTitlesList.size(); i++) {
				key = mTitlesList.get(i).getTitleId() + "";
				value = mTitlesList.get(i).getTitleName();
				dataMap.put(key, value);
			}
		}
		return dataMap;
	}

	/**
	 * 提交举报
	 */
	public void uploadReport(String nameplate_img) {

		String reportTypeName = getText(mTvReportCategory);
		String reportTitleName = getText(mTvreportThemes);
		String reportTypeId = getTag(mTvReportCategory);
		String reportTitleId = getTag(mTvreportThemes);

		// 提交举报
		RequstClient.submitReport(goods_id, AppContext.userId, reportTypeId + "", reportTitleId + "", nameplate_img, "2", mEtReportMessage.getText().toString(), reportTypeName, reportTitleName, new MyCustomResponseHandler(this, true) {

			@Override
			public void onFinish() {
				super.onFinish();
			}

			@Override
			public void onSuccess(int statusCode, Header[] headers, String content) {
				super.onSuccess(statusCode, headers, content);
				Log.d(TAG, "提交返回信息：msg:" + content);
				try {
					JSONObject obj = new JSONObject(content);
					if (!obj.getString("type").equals("1")) {
						String errorMsg = obj.getString("msg");
						Toast.makeText(ReportActivity.this, "举报提交失败，error：" + errorMsg, Toast.LENGTH_SHORT).show();
						Log.d(TAG, "提交审核失败,jsonString = " + content);
						return;
					} else {
						final UploadSuccessDialog dialog = new UploadSuccessDialog(ReportActivity.this);
						dialog.setOnClickListener(new OnClickListener() {

							@Override
							public void onClick(View arg0) {
								dialog.dismiss();
								ReportActivity.this.finish();
							}
						});
						dialog.show();
						Log.d(TAG, "提交审核成功，jsonString = " + content);
					}

				} catch (Exception e) {
					e.printStackTrace();
					Log.d(TAG, "提交请求出错，error:" + e);
				}
			}
		});
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		Log.d("base", "onKeyDown == >");
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			if (UIHelper.mLoadDialog != null && UIHelper.mLoadDialog.isShowing()) {
				Log.d("base", "KeyEvent.KEYCODE_BACK clicked, close dialog");
				UIHelper.cloesLoadDialog();
			} else {
				Log.d("base", "KeyEvent.KEYCODE_BACK clicked, finish");
				this.finish();
			}
		}
		return true;
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		switch (parent.getId()) {
		case R.id.upload_gridview:

			// 上传图片
			if (uploadImageAdapter.isClickAddPic(position)) {

				// 打开相册，相机
				showCameraPopwindow(view, false, false);
			}
			break;
		}
	}

	@Override
	public void onUpLoadSuccess(String imageUrl, String imageFile) {

		// 非空判断
		if (TextUtils.isEmpty(imageUrl) && TextUtils.isEmpty(imageFile)) {
			return;
		}

		// 显示新增的数据
		uploadImageAdapter.appendData(new ImageData(imageFile, imageUrl));
	}
}
